package top.iszsq.magic_api.provider;

import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.model.JsonBean;
import org.ssssssss.magicapi.model.Page;
import org.ssssssss.magicapi.model.RequestEntity;
import org.ssssssss.magicapi.provider.ResultProvider;
import top.iszsq.base.exceptions.BizException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口执行结果处理
 * @author zsq
 * @date 2021/12/2 16:08
 **/
@Component
public class MyResultProvider implements ResultProvider {

    /**
     * 接口发生错误
     * @param requestEntity
     * @param e
     * @return
     */
    @Override
    public Object buildException(RequestEntity requestEntity, Throwable e) {
        if (e == null) {
            return null;
        }
        Throwable cause = e.getCause();
        String message = "系统异常";
        if (cause != null && cause instanceof BizException) {
            message = cause.getMessage();
        }
        return buildResult(requestEntity, 500, message);
    }

    /**
     * 返回
     * @param requestEntity
     * @param code
     * @param message
     * @param data
     * @return
     */
    @Override
    public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
        long timestamp = System.currentTimeMillis();
        return new JsonBean<>(code, message, data, (int) (timestamp - requestEntity.getRequestTime()));
    }

    /**
     *   定义分页返回结果，该项会被封装在Json结果内，
     *   此方法可以不覆盖，默认返回PageResult
     */
    @Override
    public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
        return new HashMap<String,Object>(){
            {
                put("total", total);
                put("records", data);
            }
        };
    }
}
